package academic.emailClient.control.listeners;

import java.awt.event.*;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import academic.emailClient.model.EmailClientModel;
import academic.emailClient.view.EmailClientViewInterface;

/**
 * This class is used to listen to user click and detect the pattern ${...} and highlight it to ease replacing it with user input.
 * This class is meant to make it easy for users to replace template variable only by one random mouse click on the text area field 
 * @author o_elhali
 *
 */
public class LetterMouseListener implements MouseListener {
		EmailClientViewInterface view;
		EmailClientModel model;
		String  PATTERN = "${...}";

		/**
		 * Constructor
		 * @param view
		 * @param model
		 */
	    public LetterMouseListener(EmailClientViewInterface view,
			EmailClientModel model) {
			 this.view= view;
			 this.model =model;
	}
	    /**
	     * Handle the user mouse click by finding the first pattern occurent and highlight it and wait for user input
	     */
		public void mouseClicked(MouseEvent e){
			int pos = 0;
			Document doc = view.getLetterField().getDocument();
		    String text ="";
			try {
				text = doc.getText(0, doc.getLength());
			} catch (BadLocationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    pos = text.toUpperCase().indexOf(PATTERN.toUpperCase(), pos);
		    if(pos>=0){
		    	view.getLetterField().setCaretPosition(pos);
				view.getLetterField().moveCaretPosition(pos + PATTERN.length());	
		    }
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
	   

}
